const { exec} = require('../data/mysql')
const xss = require('xss')
 

const getList = (author,keyword) => {
    //先返回假数据，格式是正确的
    //1=1站位 可能author和keyword没值，where直接加order报错
    console.log('jinlai')
    let sql = `select * from blogs where 1=1 `
    if(author) {
        sql += `and author = '${author}'`
    }
    if(keyword) {
        sql += `and title like '%${keyword}%';`
    }
   // sql += `order by createtime desc`
    //返回promise对象
    return exec(sql)
}

const getDetail = (id) => {
    let sql = `select * from blogs where id = '${id}';`
    return exec(sql).then(rows => {
        return rows[0]
    })
}

const newBlog = (postData) => {
    postData = postData || {}
    //console.log(postData)
    //postData是一个博客对象
    const title = xss(postData.title)
    const {content, author} = postData
    const createtime = Date.now()
    const sql = `insert into blogs (title, content, createtime, author) values('${title}', '${content}', '${createtime}', '${author}');`
    return exec(sql).then(insertRes => {
    //   console.log(insertRes) 
    //    OkPacket {
    //     fieldCount: 0,
    //     affectedRows: 1,
    //     insertId: 7,
    //     serverStatus: 2,
    //     warningCount: 0,
    //     message: '',
    //     protocol41: true,
    //     changedRows: 0
    //   }
      return {
          id: insertRes.insertId,
      }
    })
    // return {
    //     id: 4 //新建博客
    // }
}

const updateBlog = (id, blogData) => {
    //id是更新博客的id
    //blogdata是博客对象，title,content
    //console.log(id,blogData)
    const {title , content} = blogData
    const sql = `update blogs set title='${title}', content = '${content}' where id = ${id};`
    return exec(sql).then(updateRes => {
        // console.log(updateRes)
        // OkPacket {
        //     fieldCount: 0,
        //     affectedRows: 1,
        //     insertId: 0,
        //     serverStatus: 2,
        //     warningCount: 0,
        //     message: '(Rows matched: 1  Changed: 1  Warnings: 0',
        //     protocol41: true,
        //     changedRows: 1
        //   }
        return updateRes.affectedRows > 0
    })
    // return true
}

const delBlog = (id,author) => {
    //删除博客的id
    //加author是为了用户登陆的自己的名字，以防删错
    const sql = `delete from blogs where id='${id}' and author = '${author}';`
    return exec(sql).then(deleRes => {
        return deleRes.affectedRows > 0
    })
    //  return true
    // return false
}
module.exports = {
    getList,
    getDetail,
    newBlog,
    updateBlog,
    delBlog
}